<style scoped>
h1 {
  text-align: center;
  margin-top: 2.5%;
}
.projectForm {
  width: 60%;
  margin-top: 40px;
  margin-left: 20%;
  margin-right: 20%;
}
.projectForm>>>.ivu-form-item-label {
  font-size: 16px;
}
.inline_style {
  display: flex;
}
.create {
  width: 20%;
  margin-right: 40%;
  margin-left: 40%;
}
#editor {
  /* position:fixed; */
  margin: 20px auto;
  bottom: 0;
  width: 80%;
  /* height: 200px; */
}
/* 上传图片 */
.demo-upload-list {
  display: inline-block;
  width: 60px;
  height: 60px;
  text-align: center;
  line-height: 60px;
  border: 1px solid transparent;
  border-radius: 4px;
  /* overflow-x: hidden; */
  /* overflow-y: scroll; */
  background: #fff;
  position: relative;
  box-shadow: 0 1px 1px rgba(0, 0, 0, 0.2);
  margin-right: 4px;
}
.demo-upload-list img {
  width: 100%;
  height: 100%;
}
.demo-upload-list-cover {
  display: none;
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.6);
}
.demo-upload-list:hover .demo-upload-list-cover {
  display: block;
}
.demo-upload-list-cover i {
  color: #fff;
  font-size: 20px;
  cursor: pointer;
  margin: 0 2px;
}
.uploadAvatar {
  position: relative;
  width: 58px;
  height: 58px;
  top: 0;
  left: 0;
  outline: none;
  background-color: transparent;
  opacity: 0;
}
.uploadBox {
  display: inline-block;
  width: 58px;
  height: 58px;
  line-height: 58px;
  border-width: 0.75px;
  border-style: dashed;
  border-color: lightslategray;
}

/* 结束 */
</style>
<template>
  <div class="project form">
    <h1>创建课程</h1>
    <div>
      <Form
        ref="formInline"
        :model="formInline"
        :rules="newClassRule"
        class="projectForm"
      >
        <FormItem prop="name" label="课程名称" :label-width="100">
          <Input
            v-model="formInline.name"
            placeholder="输入课程名称（少于 20 个字）..."
          />
        </FormItem>
        <FormItem prop="privacy" label="课程权限" :label-width="100">
          <RadioGroup v-model="formInline.privacy">
            <Radio label="public" style="font-size:18px;">自由加入</Radio>
            <Radio label="private" style="font-size:18px;">邀请加入</Radio>
          </RadioGroup>
        </FormItem>
        <FormItem prop="description" label="课程概述" :label-width="100">
          <Input
            v-model="formInline.description"
            type="textarea"
            placeholder="输入课程概述..."
          />
        </FormItem>
        <FormItem prop="classTarget" label="课程目标" :label-width="100">
          <Input
            v-model="formInline.classTarget"
            type="textarea"
            placeholder="输入课程目标..."
          />
        </FormItem>
        <!-- <FormItem prop="teachers" label="任课老师" :label-width="100">
          <Input
            v-model="formInline.teachers"
            placeholder="输入任课老师姓名..."
          />
        </FormItem> -->
        <FormItem prop="teachers" label="任课老师" :label-width="100">
            <!-- <el-input
              v-model="inputTag"
              placeholder="输入一些标签来描述作品..."
              style="width: 400px"
              @keyup.enter="addTag(inputTag)"
            /> -->
            <el-autocomplete
              
              class="inline-input"
              v-model="inputTag"
              :fetch-suggestions="querySearch"
              placeholder="输入一些标签来描述数据..."
              :trigger-on-focus="false"
              @select="handleSelect"
              @enter="addTag(inputTag)"
              style="width: 400px"
            ></el-autocomplete>
            <Button
              icon="ios-add"
              type="dashed"
              size="small"
              @click="addTag(inputTag)"
              style="margin-left: 2.5%"
              >添加老师</Button
            >
            <div>
              <Tag
                color="primary"
                v-for="(item, index) in this.formInline.teachers"
                :key="index"
                closable
                @on-close="deleteTag(index)"
                >{{ item }}</Tag
              >
            </div>
        </FormItem>
        <FormItem prop="image" label="课程图片" :label-width="100">
          <div class="inline_style">
            <div class="demo-upload-list" v-if="img != ''">
              <template>
                <img v-bind:src="img" />
                <div class="demo-upload-list-cover">
                  <Icon
                    type="ios-eye-outline"
                    @click.native="handleView()"
                  ></Icon>
                  <Icon
                    type="ios-trash-outline"
                    @click.native="handleRemove()"
                  ></Icon>
                </div>
              </template>
            </div>
            <div class="uploadBox">
              <Icon
                type="ios-camera"
                size="20"
                style="position: absolute; margin: 18px"
              ></Icon>
              <input
                id="choosePicture"
                @change="uploadPhoto($event)"
                type="file"
                class="uploadAvatar"
                accept="image/*"
              />
            </div>
            <br />
          </div>
        </FormItem>
        <FormItem>
          <div class="inline_style"  style="margin-top: 20px;">
            <Button
              @click="back2List"
              style="margin-left:35%; width: 150px;"
              >取消</Button
            >
            <Button
              type="success"
              @click="createProject('formInline')"
              style="margin-left:15px; width: 150px;"
              >保存</Button
            >
          </div>
        </FormItem>
      </Form>
    </div>
    <Modal title="View Image" v-model="visible">
      <img :src="img" v-if="visible" style="width: 100%" />
    </Modal>
  </div>
</template>


<script>
import { get, post, del, put } from "@/axios";

export default {
  data() {
    return {
      userInfo: JSON.parse(localStorage.getItem("userInfo")),
      formInline: {
        name: "",
        privacy: "public",
        description: "",
        classTarget: "",
        teachers: [],
        autoJoinin: false,
        //tag列表
        tagList: [],
      },
      newClassRule: {
        name: [
          {
            required: true,
            message: "课程名称不能为空，且少于20个字",
            trigger: "blur",
            max: 60,
          },
        ],
        privacy: [
          {
            required: true,
          },
        ],
        description: [
          {
            required: true,
            message: "课程概述不能为空，且少于180字",
            trigger: "blur",
            max: 360,
          },
        ],
        classTarget: [
          {
            required: true,
            message: "课程目标不能为空，且少于180字",
            trigger: "blur",
            max: 360,
          },
        ],
      },
      toUploadFiles: [],
      fileCountTimer: null,
      //用来存储输入的单个标签变量
      visible: false,
      //表示图片
      img: "",
      pictureUrl: "",
      imageFile: null,
      createProjectInfo: {},
      inputTag:"",
      restaurants: [],
    };
  },
  created() {
    // 加入判断，如果未登录自动跳转登录页面
    if (!this.$store.getters.userState) {
      this.$router.push({ name: "Login" });
    }
    this.getTeachersList();

    Array.prototype.contains = function (obj) {
      var i = this.length;
      while (i--) {
        if (this[i] != undefined && this[i] === obj) {
          return true;
        }
      }
      return false;
    };
  },
  mounted() {
    this.checkUserRole();
  },
  methods: {
    async getTeachersList() {
      try {
        let res = await get("/visualResourceLibrary/user/getTeachers");
        // console.log(res);
        let list = res.data.data;
        for(let i = 0 ; i < list.length ; i++){
          let item = {};
          item.value = list[i].name + '(' + list[i].userId + ')';
          item.label = list[i].name + '(' + list[i].userId + ')';
          item.id = list[i].userId;
          this.restaurants.push(item);
        }
        
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    checkUserRole() {
      //根据userId重新请求后台数据库，验证角色
      let role = this.userInfo.role;
      if (role != "admin" && role != "teacher") {
        this.$router.go(-1);
        this.$Message.error("您不是管理员，没有权限进行该操作！");
      }
      if(role == "teacher"){
        this.formInline.teachers.push(this.userInfo.name + '(' + this.userInfo.userId + ')');
      }
    },
    createProject(name) {
      this.$refs[name].validate((valid) => {
        if (valid) {
          this.commitClass();
        } else {
          this.$Message.error("创建失败");
        }
      });
    },
    querySearch(queryString, cb) {
      var restaurants = this.restaurants;
      var results = queryString
        ? restaurants.filter(this.createFilter(queryString))
        : restaurants;
      // 调用 callback 返回建议列表的数据
      cb(results);
    },
    createFilter(queryString) {
      return (restaurant) => {
        return (
          restaurant.value.toLowerCase().indexOf(queryString.toLowerCase()) ===
          0
        );
      };
    },
    addTag(tag) {
      // console.log(this.formInline);
      if (tag != "" && this.formInline.teachers.toString().indexOf(tag) == -1) {
        this.formInline.teachers.push(tag);
        this.inputTag = "";
      }
    },
    handleSelect(item) {
      this.addTag(item.value);
      this.inputTag = "";
    },
    async commitClass() {
      let formData = new FormData();
      formData.append("image", this.imageFile);
      formData.append("name", this.formInline.name);
      formData.append("privacy", this.formInline.privacy);
      formData.append("description", this.formInline.description);
      formData.append("classTarget", this.formInline.classTarget);
      formData.append("teachers", this.formInline.teachers.toString());
      try {
        let res = await post("/visualResourceLibrary/class", formData);
        // console.log(res);
        this.$Message.success("创建成功");
        this.$router.go(-1);
      } catch (e) {
        this.$Message.error("修改失败");
        console.log(e);
      }
    },
    deleteTag(index) {
      this.formInline.teachers.splice(index, 1);
    },
    uploadPhoto(e) {
      let file = e.target.files[0];
      let filesize = file.size;
      if (filesize > 21014400) {
        // 图片大于2MB
        this.$Message.error("size > 20MB");
      } else {
        var reader = new FileReader();
        reader.readAsDataURL(file);
        reader.onload = (e) => {
          this.img = e.target.result;
          this.pictureUrl = e.target.result;
          this.imageFile = file;
        };
      }
    },
    handleView() {
      this.visible = true;
    },
    handleRemove() {
      this.img = "";
      this.pictureUrl = "";
      this.imageFile = null;
    },
    back2List(){
      this.$router.go(-1);
    }
  },
};
</script>
